<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\library\Word;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 跟踪
 *
 * @icon fa fa-circle-o
 */
class Track extends Backend
{

    /**
     * Track模型对象
     * @var \app\admin\model\Track
     */
    protected $model = null;
    protected $auth_unit_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Track;
        $this->departmentList = $this->model->allDepartmentName();
        $this->view->assign("departmentList", $this->departmentList);
        $this->view->assign('initiator_id', \think\Session::get()['admin']['id']);
        //查询当前单位，判断是admin或者是规划处
        if($this->auth->id > 1) {
            $this->auth_unit_id = Db::name("department_admin")->where('admin_id',$this->auth->id)->value('department_id');
            if($this->auth_unit_id === 1) {
                //判断是规划处，放开单位选择
                unset($this->auth_unit_id);
            }
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $filter = [];
            if(!empty($this->auth_unit_id)){
                $filter['participating_departments'] = $this->auth_unit_id;
            }

            $list = $this->model
                    ->alias('track')
                    ->with(['admin','cooperation'])
                    ->where($where)
                    ->where(function($q) use ($filter) {
                        if (isset($filter['participating_departments'])) {
                            if (is_array($filter['participating_departments'])) {
                                $q->whereIn('track.participating_departments', $filter['participating_departments']);
                            }
                            else {
                                $q->where('track.participating_departments',$filter['participating_departments']);
                            }
                        }
                    })
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['nickname']);
                $row->getRelation('cooperation')->visible(['cname']);
                if(isset($row->participating_departments) && !empty($row->participating_departments)) {
                    $department_arr = explode(',', $row->participating_departments);
                    $department = '';
                    foreach ($department_arr as $depart) {
                        $departName = Db::name("department")->where('id', $depart)->value('name');
                        if ($department) {
                            $department .= ',' . (isset($departName) ? $departName : '未知');
                        } else {
                            $department = isset($departName) ? $departName : '未知';
                        }
                    }
                    $row->participating_departments = $department;
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['participating_departments'] = implode(',',$params['participating_departments']);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $id = $this->model->id;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        //增加明细
        if($id >0) {
            $department_Arr = explode(',',$params['participating_departments']);
            $insertData = [];
            foreach ($department_Arr as $value) {
                $insertData[] = [
                    'track_id'         => $id,
                    'department_id'    => $value,
                    'year'             => $params['year'],
                    'createtime'       => time(),
                    'updatetime'       => time(),
                    'endtime'          => strtotime($params['endtime']),
                ];
            }
            //增加明细
            Db::name("track_detail")->insertAll($insertData);
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $this->modelValidate = true;
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['participating_departments'] = implode(',',$params['participating_departments']);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    $id = $params['id'];
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //增加明细
                    if($id >0) {
                        //将所有数据删除
                        Db::name("track_detail")->where('track_id',$id)->update(['deletetime'=>time()]);
                        $department_Arr = explode(',',$params['participating_departments']);
                        $insertData = [];
                        foreach ($department_Arr as $value) {
                            $info = Db::name("track_detail")->where('department_id',$value)->where('track_id',$id)->find();
                            if(empty($info)) {
                                $insertData[] = [
                                    'track_id'         => $id,
                                    'department_id'    => $value,
                                    'year'             => $params['year'],
                                    'createtime'       => time(),
                                    'updatetime'       => time(),
                                    'endtime'          => strtotime($params['endtime']),
                                ];
                            }
                            else {
                                Db::name("track_detail")->where('department_id',$value)->where('track_id',$id)->update(['updatetime'=>time(),'deletetime'=>null,'endtime'=>strtotime($params['endtime'])]);
                            }
                        }
                        //增加明细
                        Db::name("track_detail")->insertAll($insertData);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('departmentList', build_select('row[participating_departments][]',$this->departmentList, $row['participating_departments'], ['class' => 'form-control selectpicker','multiple'=>'']));
        return parent::edit($ids);
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            //同步删除原有的明细记录
            //将所有数据删除
            Db::name("track_detail")->where('track_id',$ids)->delete();
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 预览word
     *
     * @param $ids
     */
    public function previewWord()
    {
        $ids = $this->request->request('ids');
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        //获取跟踪基本信息
        $data = Db::name('track_detail')
            ->alias('detail')
            ->join('fa_department department', 'detail.department_id = department.id', 'LEFT')
            ->field('department.name,detail.preparer,detail.previous_years,detail.that_year,detail.next_step,detail.other')
            ->where('detail.track_id',$row['id'])
            ->where('detail.deletetime','null')
            ->select();

        //获取合作名称
        $cname = Db::name("cooperation")->where('id',$row['cooperation_id'])->value('cname');
        //处理打印信息
        $extData = [];
        $extData['name'] = $cname ?? '';
        $extData['main_matters'] = $row['main_matters'] ?? '';
        $extData['previous'] = '';
        $extData['that'] = '';
        $extData['next'] = '';
        $extData['other'] = '';

        if(isset($data[0])) {
            foreach ($data as $k => $info) {
                //查询人员信息
                if(isset($info['preparer']) && !empty($info['preparer'])) {
                    $preparer_arr = explode(',', $info['preparer']);
                    $preparer = '';
                    foreach ($preparer_arr as $pre) {
                        $preName = Db::name("admin")->where('id',$pre)->value('nickname');
                        if($preparer) {
                            $preparer .= ','.(isset($preName) ? $preName : '未知');
                        }
                        else{
                            $preparer = isset($preName) ? $preName : '-';
                        }
                    }
                    $info['preparer'] = $preparer;
                }

                if(empty($extData['previous'])) {
                    $extData['previous'] = '【'.$info['name'].'】'.$info['preparer'].$info['previous_years'];
                }
                else {
                    $extData['previous'] = $extData['previous'].'【'.$info['name'].'】'.$info['preparer'].$info['previous_years'];
                }

                if(empty($extData['previous'])) {
                    $extData['that'] = '【'.$info['name'].'】'.$info['preparer'].$info['that_year'];
                }
                else {
                    $extData['that'] = $extData['that'].'【'.$info['name'].'】'.$info['preparer'].$info['that_year'];
                }

                if(empty($extData['previous'])) {
                    $extData['next'] = '【'.$info['name'].'】'.$info['preparer'].$info['next_step'];
                }
                else {
                    $extData['next'] = $extData['next'].'【'.$info['name'].'】'.$info['preparer'].$info['next_step'];
                }

                if(empty($extData['other'])) {
                    $extData['other'] = '【'.$info['name'].'】'.$info['preparer'].$info['other'];
                }
                else {
                    $extData['other'] = $extData['other'].'【'.$info['name'].'】'.$info['preparer'].$info['other'];
                }
            }
        }

        $word = new Word();
        $word->start();
        $word->writeTrackContent($data, $extData);
    }

    /**
     * 下载word
     *
     * @param $ids
     */
    public function downloadWord()
    {
        $ids = $this->request->request('ids');
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        //获取跟踪基本信息
        $data = Db::name('track_detail')
            ->alias('detail')
            ->join('fa_department department', 'detail.department_id = department.id', 'LEFT')
            ->field('department.name,detail.preparer,detail.previous_years,detail.that_year,detail.next_step,detail.other')
            ->where('detail.track_id',$row['id'])
            ->where('detail.deletetime','null')
            ->select();

        //获取合作名称
        $cname = Db::name("cooperation")->where('id',$row['cooperation_id'])->value('cname');
        //处理打印信息
        $extData = [];
        $extData['name'] = $cname ?? '';
        $extData['main_matters'] = $row['main_matters'] ?? '';
        $extData['previous'] = '';
        $extData['that'] = '';
        $extData['next'] = '';
        $extData['other'] = '';

        if(isset($data[0])) {
            foreach ($data as $k => $info) {
                //查询人员信息
                if(isset($info['preparer']) && !empty($info['preparer'])) {
                    $preparer_arr = explode(',', $info['preparer']);
                    $preparer = '';
                    foreach ($preparer_arr as $pre) {
                        $preName = Db::name("admin")->where('id',$pre)->value('nickname');
                        if($preparer) {
                            $preparer .= ','.(isset($preName) ? $preName : '未知');
                        }
                        else{
                            $preparer = isset($preName) ? $preName : '-';
                        }
                    }
                    $info['preparer'] = $preparer;
                }

                if(empty($extData['previous'])) {
                    $extData['previous'] = '【'.$info['name'].'】'.$info['preparer'].$info['previous_years'];
                }
                else {
                    $extData['previous'] = $extData['previous'].'【'.$info['name'].'】'.$info['preparer'].$info['previous_years'];
                }

                if(empty($extData['previous'])) {
                    $extData['that'] = '【'.$info['name'].'】'.$info['preparer'].$info['that_year'];
                }
                else {
                    $extData['that'] = $extData['that'].'【'.$info['name'].'】'.$info['preparer'].$info['that_year'];
                }

                if(empty($extData['previous'])) {
                    $extData['next'] = '【'.$info['name'].'】'.$info['preparer'].$info['next_step'];
                }
                else {
                    $extData['next'] = $extData['next'].'【'.$info['name'].'】'.$info['preparer'].$info['next_step'];
                }

                if(empty($extData['other'])) {
                    $extData['other'] = '【'.$info['name'].'】'.$info['preparer'].$info['other'];
                }
                else {
                    $extData['other'] = $extData['other'].'【'.$info['name'].'】'.$info['preparer'].$info['other'];
                }
            }
        }

        $filename = "金陵科技学院对外合作项目执行情况登记表";
        header('pragma:public');
        header('Content-type:application/vnd.ms-word;charset=utf-8;name="'.$filename.'".doc');
        header("Content-Disposition:attachment;filename=$filename.doc");

        $word = new Word();
        $word->start();
        $word->downTrackContent($data, $extData);
    }
}
